package com.example.administrator.zhjt.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.administrator.zhjt.bean.Bill;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/16 0016.
 */

public class BillDB extends SQLiteOpenHelper implements DB<Bill>{

    public static final String BILL_TABLE="bill_table";
    public static final String KEY_ID="id";
    public static final int KEY_VERSION=1;
    public static final String KEY_CARID="carid";
    public static final String KEY_MONEY="money";
    public static final String KEY_USER="user";
    public static final String KEY_TIME="createAt";

    public static final String Create_TABLE="create table "+BILL_TABLE
            +"("+KEY_ID+" integer primary key autoincrement,"
            +KEY_CARID+" integer,"
            +KEY_MONEY+" integer,"
            +KEY_USER+" integer,"
            +KEY_TIME+" long);";

    public BillDB(Context context){
        super(context,Create_TABLE,null,KEY_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Create_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private static BillDB instance;
    public static BillDB getInstance(Context context){
        if (instance==null){
            instance=new BillDB(context);
        }
        return instance;
    }

    @Override
    public void create(Bill object) {
        getWritableDatabase().insert(BILL_TABLE,null,object.toContentValues());
    }

    @Override
    public void update(Bill object) {

    }

    @Override
    public Bill read(int id) {
        return null;
    }

    @Override
    public List<Bill> list(String order) {
        List<Bill> list=new ArrayList<>();
        SQLiteDatabase database=getReadableDatabase();
        Cursor cursor=database.rawQuery("select * from "+BILL_TABLE+" order by "+ KEY_MONEY +" "+order,null);
        while (cursor.moveToNext()){
            Bill bill=new Bill();
            list.add(bill.formCursor(cursor));
        }
        cursor.close();
        database.close();
        return list;
    }

    @Override
    public void delete(int id) {

    }
}
